<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Shop extends MY_Controller {

    public function __construct()
    {
        parent::__construct();
		$this->load->library('tank_auth');
		//$this->lang->load('tank_auth');
        if(!$this->tank_auth->is_logged_in() || !$this->tank_auth->is_admin())
            redirect('administrator/auth');
        $this->load->model('categories','cat');
        $this->load->model('tank_auth/roles','rol');
        $this->load->model('products','pro');
        $this->load->model('promotions','prom');
        $this->load->model('comment');
    }
    /**
     * Default function
     */
    public function index()
    {
		
    }
    
    
    /**
    *Proudct
    */
    public function product($act = false){
        $post= $this->input->post(null);
        $this->_layout['action'] = $this->uri->segment(4);
        $this->_layout['product_id'] = $this->uri->segment(5);
        
        $categories = $this->cat->getCat(array('cat_type'=>'shop'));
        $products = $this->pro->getProduct();
        $this->assign('products',$products);
        $this->assign('action','');
        
        if($act)
        {   
            $this->_layout['roles']=$this->rol->get_roles();
            $this->_layout['categories'] = $categories;
            if($act!="detail"){
            if($act=="save"){
                
                switch ($post['action']) {
                    case 'create':
                        if($post['product_name'] ==""){
                            _set_error_message('....');
                            redirect('administrator/shop/product');
                        }                   
                        $productname = $this->_global->_serialize(array($this->session->userdata('lan')=>array('product_name'=>$post['product_name'])));
                        $alias = $this->_global->_serialize(array($this->session->userdata('lan')=>array('alias'=>_set_alias($post['product_name']))));
                        $productdesc = $this->_global->_serialize(array($this->session->userdata('lan')=>array('product_desc'=>$post['product_desc'])));                                                
                        $is_feature=0;
                        if(isset($post['is_feature'])) $is_feature = $post['is_feature'];
                        $fields = array('product_name'=>$productname
                                    ,'product_alias'=>$alias
                                    ,'product_desc'=>$productdesc
                                    ,'cat_id'=>$post['cat_id']
                                    ,'price_import'=>$post['price_import']
                                    ,'price_export'=>$post['price_export']
                                    ,'price_discount'=>$post['price_discount']
                                    ,'brand_tag'=>$post['brand_tag']
                                    ,'access'=>$post['access']
                                    ,'metakey'=>$post['metakey']
                                    ,'is_feature'=> $is_feature 
                                    ,'metadesc'=>$post['metadesc']);
                        $rs = $this->pro->addProduct($fields);
                        if($rs>0){
                            if(!empty($post['brand_tag'])){
                                $arr = explode(',',$post['brand_tag']);
                                foreach($arr as $a){
                                    _insert_tags($a,'brand');   
                                }
                            }
                            _set_success_message('Save successful');
                          
                            redirect('administrator/shop/product/detail/'.$rs);
                            
                        }
                        else
                            _set_error_message('....');
                        redirect('administrator/shop/product');
                        break;
                        case 'detail':
                                               
                        $config['max_size'] ='100M';
                        $config['upload_path'] = 'cdn/uploads/'. strtoupper(dechex(sprintf("%u", crc32(date('Y-m-d')))));
                        $config['allow_type'] = array('jpg','gif','png');
                        $data = array();
                        $flag = true;                       
                        $size = array();
                        $size_tag = "";
                        $color_tag = "";
                        $tmp_size = array();
                        $old_images = $this->input->post('images');
                        
                        $options = $this->_global->_unserialize($post['product_detail']);
                        
                        if(!empty($options)){
                            if(isset($options['options']['colors'][_set_alias($post['color'])]['images']))
                                $images = $options['options']['colors'][_set_alias($post['color'])]['images'];
                            
                            $key_color = array_keys($options['options']['colors']);
                            foreach($key_color as $key){
                                $arr = array_keys($options['options']['colors'][$key]['size']);
                                
                                foreach($arr as $key=>$val){
                                    if(!in_array($val,$tmp_size)){
                                        $tmp_size[] = $val;
                                    }
                                }
                            }
                        }
                        if(!empty($_FILES)){
                            foreach($_FILES as $key=>$val){
                                
                               $dt = _upload($config,$key);
                               if($dt)
                                    $data[] = $dt['url'];
                               else
                               {
                                    if(empty($images))
                                        $flag = false;
                               }
                            }
                        }else
                            $flag = false;
                        if($flag){
                            if(!empty($images)){
                                if($old_images){
                                    foreach($images as $img){
                                        if(!in_array($img,$old_images))
                                            $size[] = $img;
                                        else
                                            @unlink($img);
                                    }
                                    $images =  $size;
                                }
                            }
                            
                        if(isset($post['sizeName']))
                        {   
                            $sizes = $post['sizeName'];}else $totalSizes = 0;
                            $totalSizes = count($sizes);
                        if(isset($post['sizeQty']))
                            $quatities = $post['sizeQty'];
                        
                        if($totalSizes>0){
                            for($i=0;$i<$totalSizes;$i++){
                                if($sizes[$i]!='' && $quatities[$i]>0){
                                    $options['options']['colors'][_set_alias($post['color'])]['size'][$sizes[$i]] = $quatities[$i];    
                                }
                            }
                        }else
                        {
                            $options['options']['colors'][_set_alias($post['color'])] = '';
                        }   
                        
                        if(!empty($images))
                            {
                                foreach($data as $da){
                                    array_push($images,$da);
                                }
                                $data = $images;
                            }
                        $options['options']['colors'][_set_alias($post['color'])]['images'] = $data;
                        $arr = array_keys($options['options']['colors'][_set_alias($post['color'])]['size']);
                       
                       foreach($arr as $key=>$val){
                            if(!in_array($val,$tmp_size)){
                                $tmp_size[] = strtolower($val);
                            }
                       }
                       $size_tag = implode(',',$tmp_size);
                       if($post['color_tag'] == "")
                            $color_tag = $post['color'];
                       else
                       {
                            $arr = explode(',',$post['color_tag']);
                            if(!in_array(strtolower($post['color']),$arr))
                                $arr[]=strtolower($post['color']);
                            $color_tag = implode(',',$arr); 
                       }
                       
                       $rs = $this->pro->updateProduct(array('product_detail'=>$this->_global->_serialize($options),'size_tag'=>$size_tag,'color_tag'=>$color_tag),array('product_id'=>$post['product_id']));
                       
                       if($rs>0){
                            _insert_tags(strtolower($post['color']),'color');
                            
                            _set_success_message('Cập nhật chi tiết sản phẩm thành công');
                        }
                            
                        else
                            _set_error_message('Không thể cập nhật sản phẩm');
                        
                        }else{
                            if(!empty($data)){
                                foreach($data as $key=>$val)
                                {
                                    @unlink($val);
                                }
                            }
                        }
                      //  unset($data,$size_tag,$arr,$old_images,$images,$tmp_size);
                        redirect('administrator/shop/product/detail/'.$post['product_id']);
                        break;
                    case 'edit':
                        $product = $this->pro->getProduct(array('product_id'=>$post['product_id']));
                        $productname = $this->_global->_unserialize($product->product_name);
                        if(!isset($productname[$this->session->userdata('lan')]))
                        {
                            //@TODO
                        }else
                            $productname[$this->session->userdata('lan')]['product_name']=$post['product_name'];
                        if(!empty($product->product_desc)){
                            $productdesc = $this->_global->_unserialize($product->product_desc);
                            if(!isset($productdesc[$this->session->userdata('lan')])){
                                //@TODO
                            }
                            else
                            $productdesc[$this->session->userdata('lan')]['product_desc']=$post['product_desc'];
                            
                        }
                        
                        $alias = $this->_global->_unserialize($product->product_alias);                     
                        if(!isset($alias[$this->session->userdata('lan')]))
                        {
                            //@TODO
                        }else
                            $alias[$this->session->userdata('lan')]['alias']=_set_alias($post['product_name']);
                        
                        
                        $productname=$this->_global->_serialize($productname);
                        $alias = $this->_global->_serialize($alias);
                        $productdesc=$this->_global->_serialize($productdesc);
                        $is_feature=0;
                        if(isset($post['is_feature'])) $is_feature = $post['is_feature'];
                        $rs = $this->pro->updateProduct(array('cat_id'=>$post['cat_id']
                                                                ,'product_name'=>$productname
                                                                ,'product_alias'=>$alias
                                                                ,'product_desc'=>$productdesc
                                                                ,'price_import'=>$post['price_import']
                                                                ,'price_export'=>$post['price_export']
                                                                ,'price_discount'=>$post['price_discount']
                                                                ,'brand_tag'=>$post['brand_tag']
                                                                ,'metakey'=>$post['metakey']
                                                                ,'is_feature'=>$is_feature
                                                                ,'metadesc'=>$post['metadesc']
                                                                ,'access'=>$post['access']),array('product_id'=>$post['product_id']));                        
                        
                        if($rs>0){
                            if(!empty($post['brand_tag'])){
                                $arr = explode(',',$post['brand_tag']);
                                foreach($arr as $a){
                                    _insert_tags($a,'brand');   
                                }
                            }
                            _set_success_message('Save successful');
                            }
                        else
                            _set_error_message('....');
                        redirect('administrator/shop/product');
                        break;
                }
                
            }elseif($act=="delete"){
                if(!is_numeric($this->_layout['product_id']) || !$this->_layout['product_id']){
                    _set_error_message('Cant delete this product');
                    redirect('administrator/shop/product');
                }
                $rs = $this->pro->deleteProduct($this->_layout['product_id']);
                if($rs>0){
                    _set_success_message('Deleted...');
                }else
                    _set_error_message('Cant delete this product');
                redirect('administrator/shop/product');
            }elseif($act=="edit"){
                $this->_layout['product'] = $this->pro->getProduct(array('product_id'=>$this->_layout['product_id']));
            }elseif($act=="create"){
                //@TODO
            }
            else show_404();
            }
            if($act=="detail"){
                $this->_layout['product_id'] == $this->uri->segment(5);
                $this->_layout['option'] = $this->uri->segment(6);
                if(!is_numeric($this->_layout['product_id']) || !$this->_layout['product_id']) show_404();
                $product = $this->pro->getProduct(array('product_id'=> $this->_layout['product_id']));
                if(empty($product)) redirect('administrator/shop/product/create');
                $this->_layout['colors'] = $this->_global->_unserialize($product->product_detail);
                $this->_layout['product'] = $product;
                $this->_layout['product_title'] = $this->_global->_unserialize($product->product_name);
                $form   = $this->load->view('layouts/form/product-color',$this->_layout,true);
                }
            elseif($act=="edit"){
                $form   = $this->load->view('layouts/form/edit-product',$this->_layout,true);
            }
            else
                $form   = $this->load->view('layouts/form/product',$this->_layout,true);
            $this->assign('action',$form);
            
        }
    }
    /**
    *Order
    */
    public function order($act = null){
        $this->load->model('orders');
        $orders = '';
        if(!$act){
            $this->assign('layout_form','layouts/form/order');
            $orders = $this->orders->getOrder();
           }
        elseif($act=='detail'){
            $this->assign('layout_form','layouts/form/order_detail');
            $orders = $this->orders->getOrder($this->uri->segment(5));
        }elseif($act=='cancel'){
            $this->assign('layout_form','layouts/form/order_cancel');
        }
        $this->assign('orders',$orders);
    }
    function updateOrder($field,$val,$order_id){
        $this->disable_view();
        $this->load->model('orders');
        
        $this->output->set_output($this->orders->updateOrder(array($field=>$val),$order_id));
       
    }
    function cancelOrder($order_id){
        $this->disable_view();
        $this->load->model('orders');
        
        $this->output->set_output($this->orders->updateOrder(array('reason_cancel'=>$this->input->post('reason'),'status'=>4),$order_id));
       
    }
    /**
    *Promotion
    */
    public function promotion($act = false){
        $post= $this->input->post(null,true);
        $this->_layout['action'] = $this->uri->segment(4);
        $this->_layout['promotion_id'] = $this->uri->segment(5);
        
        //$categories = $this->cat->getCat(array('cat_type'=>'shop'));
        $promotions = $this->prom->get_promotion();
        $this->assign('promotions',$promotions);
        $this->assign('action','');
        
        if($act)
        {   
            if($act=="save"){
                if($post['discount'] ==""){
                            _set_error_message('....');
                            redirect('administrator/shop/promotion');
                        }
                switch ($post['action']) {
                    case 'create':     
                        if($post['qty']){ 
                            for($i=0;$i<$post['qty'];$i++){
                            $code = rand(1,1001231300).strtoupper(dechex(sprintf("%u", rand(1,9999999000))));
                            $hasher = new PasswordHash(
        					$this->load->config->item('phpass_hash_strength', 'tank_auth'),
        					$this->load->config->item('phpass_hash_portable', 'tank_auth'));
    			             $hash_code = $hasher->HashPassword($code);        
                            $fields = array('promotion_code'=>$code,
                            'promotion_code_hash'=>$hash_code
                            ,'discount'=>$post['discount']
                            ,'startdate'=>strtotime($post['startdate'])
                            ,'enddate'=>strtotime($post['enddate']));
                            $rs = $this->prom->add_promotion($fields);    
                            }
                        }
                        if($rs>0)
                            _set_success_message('Save successful');
                        else
                            _set_error_message('....');
                        redirect('administrator/shop/promotion');
                        break;
                    case 'edit':
                        $rs = $this->prom->update_promotion(array('discount'=>$post['discount']
                                                                ,'startdate'=>strtotime($post['startdate'])
                                                                ,'enddate'=>strtotime($post['enddate'])),array('promotion_id'=>$post['promotion_id']));                        
                        
                        if($rs>0)
                            _set_success_message('Save successful');
                        else
                            _set_error_message('....');
                        redirect('administrator/shop/promotion');
                        break;
                }
                
            }elseif($act=="delete"){
                if(!is_numeric($this->_layout['promotion_id']) || !$this->_layout['promotion_id']){
                    _set_error_message('Cant delete this promotion');
                    redirect('administrator/shop/promotion');
                }
                $rs = $this->prom->delete_promotion($this->_layout['promotion_id']);
                if($rs){
                    _set_success_message('Deleted...');
                }else
                    _set_error_message('Cant delete this promotion');
                redirect('administrator/shop/promotion');
            }
            elseif($act=="actived"){
                if(!is_numeric($this->_layout['promotion_id']) || !$this->_layout['promotion_id']){
                    _set_error_message('Cant active this promotion');
                    redirect('administrator/shop/promotion');
                }
                $this->prom->update_promotion(array('actived'=>1),array('promotion_id'=>$this->_layout['promotion_id']));
                redirect('administrator/shop/promotion');
            }elseif($act=="unactived"){
                if(!is_numeric($this->_layout['promotion_id']) || !$this->_layout['promotion_id']){
                    _set_error_message('Cant unactived this promotion');
                    redirect('administrator/shop/promotion');
                }
               $this->prom->update_promotion(array('actived'=>0),array('promotion_id'=>$this->_layout['promotion_id']));
                redirect('administrator/shop/promotion');
            }elseif($act=="edit"){
                $this->_layout['promotion'] = $this->prom->get_promotion(array('promotion_id'=>$this->_layout['promotion_id']));
            }elseif($act=="create"){
                //@TODO
            }
            else show_404();
            $form   = $this->load->view('layouts/form/promotion',$this->_layout,true);
            $this->assign('action',$form);
            
        }
    }
    /**
    *Rate
    */
    public function comment(){
        
    }
}